unit UntIDGenerator;

interface

type
  TIDGenerator = class(TObject)
  public
    class function GeneratorID(const aTableName, aFieldName, aPrefix: string; const
        aLength: Integer = 6): String;
    class function RSNO: string;
    class function SSNO: string;
    class function ISNO: string;
    class function GRNO: string;
    class function BarCode(brand, gender: String): string;
    class function RENO: string;
    class function DINO: string;
    class function STNO: string;
  end;

implementation

uses
  UntDMDB, defineConst, SysUtils,Variants;



class function TIDGenerator.GeneratorID(const aTableName, aFieldName, aPrefix:
    string; const aLength: Integer = 6): String;
var sqlStr :String;
lstr:string;
begin
  Result := '';
  sqlStr := 'select max('+aFieldName+') '+aFieldName+' from '+aTableName+'  where '+aFieldName+' like "'+aPrefix+'%"';
  with DMMySQL.myqryCom do
  begin
    Close;
    try
      SQL.Clear;
      SQL.Add(sqlStr);
      Open;
      if not IsEmpty then
      begin
        if VarIsNull(FieldByName(aFieldName).AsVariant) or VarIsEmpty(FieldByName(aFieldName).AsVariant) then
        begin
          lstr := cStrZero + '1';
          Result := aPrefix + Copy(lstr,Length(lstr)-aLength+1,Length(lstr));
          exit;
        end;
        lstr := FieldByName(aFieldName).AsString;
        lstr := StringReplace(lstr,aPrefix,'',[rfIgnoreCase]);
        lstr := cStrZero + IntToStr(StrToInt(lstr)+1);
        Result := aPrefix + Copy(lstr,Length(lstr)-aLength+1,Length(lstr));
      end else
      begin
        lstr := cStrZero + '1';
        Result := aPrefix + Copy(lstr,Length(lstr)-aLength+1,Length(lstr));
      end;
    finally
      Close;
    end;
  end;
end;

class function TIDGenerator.RSNO: string;
begin
  Result := GeneratorID('salehd','saleNO','RS',8);
end;

class function TIDGenerator.SSNO: string;
begin
  Result := GeneratorID('salehd','saleNO','SS',8);
end;

class function TIDGenerator.ISNO: string;
begin
  Result := GeneratorID('salehd','saleNO','IS',8);
end;

class function TIDGenerator.GRNO: string;
begin
  Result := GeneratorID('purchasehd','prNO','GR',8);
end;

class function TIDGenerator.DINO: string;
begin
  Result := GeneratorID('discountinfohd','diNO','DI',8);
end;


class function TIDGenerator.BarCode(brand, gender: String): string;
var str:String;
brandCode :String ;
begin
  brandCode := DMMySQL.GetDBValue_Str('select `code` from brandInfo where active =1 and brand="'+brand+'"') ;
  str := brandCode + Copy(gender, 0, 1);
  Result := GeneratorID('goodsinfo','BarCode',str,6);
end;

class function TIDGenerator.RENO: string;
begin
  Result := GeneratorID('returnshd','reNO','RE',8);
end;

class function TIDGenerator.STNO: string;
begin
  Result := GeneratorID('stocktakinghd','STNO','ST',8);
end;

end.
